import os
import pandas as pd
import numpy as np
import requests
import json
from loader import SentimentAnalysis
sentiment=SentimentAnalysis()
def api_login(username='xiongjiaju',password='ncosstasf6'):
    try:
        url = f"https://www.xaoji.com:3306/erp/login"
        payload={
            "username":username,
            "password":password
        }
        headers = { 
            'User-Agent': 'Apifox/1.0.0 (https://www.apifox.cn)'
        }
        response = requests.post(url, headers=headers, data=payload)
        res= json.loads(response.text)
        if res['success']==False:
            raise('登录失败')
        token=res['data']['sessionid']
        os.environ['TOKEN']=token
        return token
    except:
        raise('登录失败')
api_login()
print(os.getenv('TOKEN'))
def getInput(input):
    params = '?'
    for i, key in enumerate(input):
        value = input[key]
        params += f'{key}={value}' if i == len(input) - 1 else f'{key}={value}&'
    return params
def api_getMessageList(
    startDate, endDate, pageSize=10000, page=1, type=1,
):
    url = f"https://www.xaoji.com:3306/erp/ai/getchatmessage?pageSize={pageSize}&page={page}&type={type}&startDate={startDate}&endDate={endDate}"
    payload = {}
    headers = {"User-Agent": "Apifox/1.0.0 (https://www.apifox.cn)"}

    response = requests.request("GET", url, headers=headers, data=payload)
    res = json.loads(response.text)
    if res["success"] != 200:
        raise ("请求失败")
    # pattern = r"[\【\@\[]+"
    result = {"data": res["data"], "fileNumber": 0}
    # result["data"] = list(
    #     map(lambda item: [re.sub(pattern, "", item["content"].strip()), exceptMatch], res["data"])
    # )
    return result["data"]
def api_updateEmotion(input):
    text=input['text']
    id=input['id']
    str2,score=sentiment.sentiment_analysis_single(text)
    talk_status=[{"status":str2,"value":int(score*100)}]
    url = "https://www.xaoji.com:3306/erp/topic/updateemotion"

    payload = json.dumps({
    "id": id,
    "talk_status": talk_status
    })
    headers = {
    'Authorization': os.getenv('TOKEN'),
    'User-Agent': 'Apifox/1.0.0 (https://www.apifox.cn)',
    'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)
    return json.loads(response.text)
def api_getAiTopic(input):
    print(input,'params')
    params = getInput(input)
    url = f"https://www.xaoji.com:8384/erp/topic/getaitopiclist{params}"
    payload={}
    headers = {
        'Authorization':os.getenv('TOKEN'),  # 使用输入参数中的 'token' 值作为授权头
        'User-Agent': 'Apifox/1.0.0 (https://www.apifox.cn)'
    }
    response = requests.get(url, headers=headers, data=payload)
    return response.text
def api_getAiTopic(input):
    print(input,'params')
    params = getInput(input)
    url = f"https://www.xaoji.com:8384/erp/topic/getaitopiclist{params}"
    payload={}
    headers = {
        'Authorization':os.getenv('TOKEN'),  # 使用输入参数中的 'token' 值作为授权头
        'User-Agent': 'Apifox/1.0.0 (https://www.apifox.cn)'
    }
    response = requests.get(url, headers=headers, data=payload)
    return response.text
def api_createTopicAi(input):
    url = "https://www.xaoji.com:8432/erp/topic/createaitopic"
    payload=input
    headers = {
    'Authorization': os.getenv('TOKEN'),
    'User-Agent': 'Apifox/1.0.0 (https://www.apifox.cn)'
    }

    response = requests.request("POST", url, headers=headers, data=payload)
    data=json.loads(response.text)
    return data

def api_updateaitopic(agrs):
    url=f'https://www.xaoji.com:3306/erp/topic/updateaitopic'
    payload=agrs
    headers = {
        'Authorization':os.getenv('TOKEN'),  # 使用输入参数中的 'token' 值作为授权头
        'User-Agent': 'Apifox/1.0.0 (https://www.apifox.cn)'
    }
    response = requests.post(url, headers=headers, data=payload)
    return json.loads(response.text)